package com.djf.djfcs.controller;

import com.djf.djfcs.entity.es.OrderDocument;
import com.djf.djfcs.esService.OrderEsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单Elasticsearch控制器
 * 提供订单ES文档的增删改查API
 */
@Slf4j
@RestController
@RequestMapping("/api/es/orders")
public class OrderEsController {

    @Autowired
    private OrderEsService orderEsService;

    /**
     * 创建订单索引
     */
    @PostMapping("/index")
    public ResponseEntity<Map<String, Object>> createOrderIndex() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean created = orderEsService.createOrderIndex();
            if (created) {
                result.put("success", true);
                result.put("message", "订单索引创建成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "订单索引已存在");
                return ResponseEntity.ok(result);
            }
        } catch (IOException e) {
            log.error("创建订单索引失败", e);
            result.put("success", false);
            result.put("message", "创建订单索引失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 索引订单文档（新增或更新）
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> indexOrder(@RequestBody OrderDocument orderDocument) {
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = orderEsService.indexOrder(orderDocument);
            result.put("success", true);
            result.put("message", "订单文档索引成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("索引订单文档失败", e);
            result.put("success", false);
            result.put("message", "索引订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据ID获取订单文档
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getOrderById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            OrderDocument orderDocument = orderEsService.getOrderById(id);
            if (orderDocument != null) {
                result.put("success", true);
                result.put("message", "获取订单文档成功");
                result.put("data", orderDocument);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "订单文档不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (IOException e) {
            log.error("获取订单文档失败", e);
            result.put("success", false);
            result.put("message", "获取订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据订单号获取订单文档
     */
    @GetMapping("/orderNo/{orderNo}")
    public ResponseEntity<Map<String, Object>> getOrderByOrderNo(@PathVariable String orderNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            OrderDocument orderDocument = orderEsService.getOrderByOrderNo(orderNo);
            if (orderDocument != null) {
                result.put("success", true);
                result.put("message", "获取订单文档成功");
                result.put("data", orderDocument);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "订单文档不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (IOException e) {
            log.error("获取订单文档失败", e);
            result.put("success", false);
            result.put("message", "获取订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 搜索订单文档
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchOrders(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) BigDecimal minAmount,
            @RequestParam(required = false) BigDecimal maxAmount,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "0") int from,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            List<OrderDocument> orderDocuments = orderEsService.searchOrders(
                    userId, status, productName, minAmount, maxAmount, 
                    startTime, endTime, from, size);
            
            result.put("success", true);
            result.put("message", "搜索订单文档成功");
            result.put("data", orderDocuments);
            result.put("total", orderDocuments.size());
            result.put("from", from);
            result.put("size", size);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("搜索订单文档失败", e);
            result.put("success", false);
            result.put("message", "搜索订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新订单文档
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateOrder(
            @PathVariable Long id, 
            @RequestBody Map<String, Object> updates) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = orderEsService.updateOrder(id, updates);
            result.put("success", true);
            result.put("message", "订单文档更新成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("更新订单文档失败", e);
            result.put("success", false);
            result.put("message", "更新订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 删除订单文档
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteOrder(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean deleted = orderEsService.deleteOrder(id);
            if (deleted) {
                result.put("success", true);
                result.put("message", "订单文档删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "订单文档不存在或删除失败");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (IOException e) {
            log.error("删除订单文档失败", e);
            result.put("success", false);
            result.put("message", "删除订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 批量索引订单文档
     */
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchIndexOrders(@RequestBody List<OrderDocument> orderDocuments) {
        Map<String, Object> result = new HashMap<>();
        try {
            int successCount = orderEsService.batchIndexOrders(orderDocuments);
            result.put("success", true);
            result.put("message", "批量索引订单文档完成");
            result.put("successCount", successCount);
            result.put("totalCount", orderDocuments.size());
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("批量索引订单文档失败", e);
            result.put("success", false);
            result.put("message", "批量索引订单文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 删除订单索引
     */
    @DeleteMapping("/index")
    public ResponseEntity<Map<String, Object>> deleteOrderIndex() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean deleted = orderEsService.deleteOrderIndex();
            if (deleted) {
                result.put("success", true);
                result.put("message", "订单索引删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "订单索引删除失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (IOException e) {
            log.error("删除订单索引失败", e);
            result.put("success", false);
            result.put("message", "删除订单索引失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}